import {
    GetPersonalPesources,
    DelPersonalPesources,
    SetPersonalPesources,
    UploadAvatar,
    DelPersonalModel,
    GetModelList,
    DownloadFile,
    CheckFileSize,
} from "~/api";

export const useContent = () => {
    const tabActive = ref(0);
    const list = ref([]);
    const isLoading = ref(false);
    const isBatchDelete = ref(false);
    const deleteIds = ref([]);
    const isUploading = ref(false);
    const uploadType = ref(null);
    const keyword = ref("");
    const searchKeyword = ref("");

    const materialList = reactive([
        {
            label: "图片",
            value: 1,
            maxSize: 10,
            ext: ["png", "jpg", "jpeg"],
            accept: "image/png,image/jpeg,image/jpg",
        },
        {
            label: "视频",
            value: 2,
            maxSize: 500,
            ext: ["mp4"],
            accept: "video/*",
        },
        {
            label: "音频",
            value: 4,
            maxSize: 10,
            ext: ["mp3", "wav"],
            accept: "audio/*",
        },
        {
            label: "模型",
            value: -1,
            maxSize: 30,
            ext: ["zip", "rar", "7zip"],
            accept: "application/*",
        },
        {
            label: "PDF",
            value: 5,
            maxSize: 10,
            ext: ["pdf"],
            accept: "application/pdf",
        },
        {
            label: "动图",
            value: 6,
            maxSize: 5,
            ext: ["gif"],
            accept: "image/gif",
        },
        {
            label: "3D图",
            value: 7,
            maxSize: 10,
            ext: ["png", "jpg", "jpeg"],
            accept: "image/*",
        },
    ]);

    const renderList = computed(() => {
        return list.value.filter((item) =>
            item.show_name.includes(searchKeyword.value)
        );
    });

    const onTreeClick = (value) => {
        if (open.value.includes(value)) {
            open.value = open.value.filter((item) => item !== value);
        } else {
            open.value.push(value);
        }
    };

    const GetRes = async () => {
        isLoading.value = true;
        const res = await GetPersonalPesources({
            type: materialList[tabActive.value].value,
        });
        isLoading.value = false;
        if (res.code == 200) {
            list.value = res.data.reverse();
        }
    };

    const GetModel = async () => {
        isLoading.value = true;
        const res = await GetModelList({ type: 0 });
        isLoading.value = false;
        if (res.code == 200) {
            list.value = res.data.reverse();
        }
    };

    const GetCoverImage = (item) => {
        return {
            "-1": () => ({
                cover: item.icon_url,
                origin: item.icon_url,
            }),
            1: () => ({
                cover: item.file + "?x-oss-process=image/resize,w_444",
                origin: item.file,
            }),
            2: () => ({
                cover:
                    item.file +
                    "?x-oss-process=video/snapshot,t_0,f_jpg,w_444,h_0,m_fast,ar_auto",
                origin: item.file,
            }),
            4: () => ({
                origin: item.file,
            }),
            5: () => ({
                cover: item.icon,
                origin: item.file,
            }),
            6: () => ({
                cover: item.file,
                origin: item.file,
            }),
            7: () => ({
                cover: item.file,
                origin: item.file,
            }),
        }[materialList[tabActive.value].value]();
    };

    const onCancelBatchDelete = () => {
        isBatchDelete.value = false;
        deleteIds.value = [];
    };

    const onDeleteCheck = (id) => {
        if (deleteIds.value.includes(id)) {
            deleteIds.value = deleteIds.value.filter((item) => item !== id);
        } else {
            deleteIds.value.push(id);
        }
    };

    const onTabActive = (value) => {
        tabActive.value = value;
        list.value = [];
        deleteIds.value = [];
        if (materialList[tabActive.value].value == -1) {
            GetModel();
        } else {
            GetRes();
        }
    };

    const onDelete = async () => {
        if (deleteIds.value.length == 0) {
            Message().warning("请选择要删除的文件");
        } else {
            if (materialList[tabActive.value].value === -1) {
                const res = await DelPersonalModel({
                    id: deleteIds.value.join(","),
                });
                if (res.code == 200) {
                    Message().success("删除成功");
                    GetModel();
                    onCancelBatchDelete();
                }
            } else {
                const res = await DelPersonalPesources({
                    rids: deleteIds.value.join(","),
                });
                if (res.code == 200) {
                    Message().success("删除成功");
                    GetRes();
                    onCancelBatchDelete();
                }
            }
        }
    };

    const uploadFile = (file) => {
        const formData = new FormData();
        formData.append("file", file);
        return UploadAvatar(formData);
    };

    const onSelectFile = async (e) => {
        try {
            let files = [...e.target.files];
            uploadType.value = tabActive.value;
            isUploading.value = true;
            for (let i = 0; i < files.length; i++) {
                let file = files[i];
                let fileName = file.name.split(".").shift();
                let ext = materialList[uploadType.value].ext;

                if (
                    ext.findIndex((e) => new RegExp(e, "i").test(file.name)) ==
                    -1
                ) {
                    Message().warning(
                        file.name + "文件格式不正确，如有问题请联系客服"
                    );
                    continue;
                }

                // 检查是否可以上传
                const res = await CheckFileSize({
                    size: (file.size / 1024 / 1024).toFixed(2),
                });
                if (res.code == 200) {
                    if (
                        file.size >
                        materialList[uploadType.value].maxSize * 1024 * 1024
                    ) {
                        Message().warning(
                            file.name +
                            "文件大小超过" +
                            materialList[uploadType.value].maxSize +
                            "MB"
                        );
                        continue;
                    } else {
                        let icon = "";
                        let url = "";

                        if (
                            [1, 7].includes(
                                materialList[uploadType.value].value
                            )
                        ) {
                            const fileRes = await uploadFile(file);
                            const thumbBlob = await DownloadFile(
                                fileRes.data.fullurl +
                                "?x-oss-process=image/resize,w_480"
                            );

                            let iconRes = await uploadFile(
                                new File([thumbBlob], fileName + ".jpg", {
                                    type: "image/jpeg",
                                })
                            );
                            icon = iconRes.data.url;
                            url = fileRes.data.url;
                        } else if (
                            [2].includes(materialList[uploadType.value].value)
                        ) {
                            const fileRes = await uploadFile(file);
                            let thumbBlob = null;
                            try {
                                thumbBlob = await DownloadFile(
                                    fileRes.data.fullurl +
                                    "?x-oss-process=video/snapshot,t_0,f_jpg,w_480,h_0,m_fast,ar_auto"
                                );
                            } catch (e) {
                                thumbBlob = await DownloadFile(
                                    _oss_ +
                                    "images/admin/material-store/video-bg.jpg"
                                );
                            }

                            let iconRes = await uploadFile(
                                new File([thumbBlob], fileName + ".jpg", {
                                    type: "image/jpeg",
                                })
                            );
                            icon = iconRes.data.url;
                            url = fileRes.data.url;
                        } else if (
                            [4, 5].includes(
                                materialList[uploadType.value].value
                            )
                        ) {
                            const fileRes = await uploadFile(file);
                            url = fileRes.data.url;
                        } else if (
                            [6].includes(materialList[uploadType.value].value)
                        ) {
                            const fileRes = await uploadFile(file);
                            const thumbBlob = await DownloadFile(
                                fileRes.data.fullurl +
                                "?x-oss-process=image/resize,w_480"
                            );

                            let iconRes = await uploadFile(
                                new File([thumbBlob], fileName + ".png", {
                                    type: "image/png",
                                })
                            );
                            icon = iconRes.data.url;
                            url = fileRes.data.url;
                        }

                        await SetPersonalPesources({
                            show_name: fileName,
                            type: materialList[uploadType.value].value,
                            file: url,
                            icon,
                        });
                    }
                } else {
                    Message().warning(res.msg);
                    return;
                }
            }
            await GetRes();
            e.srcElement.value = "";
            isUploading.value = false;
        } catch (e) {
            Message().error("上传失败");
            isUploading.value = false;
        }
    };

    const onSearch = () => {
        searchKeyword.value = keyword.value;
    };

    return {
        tabActive,
        list,
        renderList,
        materialList,
        isLoading,
        isUploading,
        isBatchDelete,
        deleteIds,
        keyword,
        onSelectFile,
        onDelete,
        onSearch,
        onTreeClick,
        onDeleteCheck,
        onTabActive,
        onCancelBatchDelete,
        GetRes,
        GetModel,
        GetCoverImage,
    };
};
